<?php

namespace app\admin\model;

use app\common\model\Category;
use think\Model;
use traits\model\SoftDelete;

class Article extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'article';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'tags_data_text',
        'status_data_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }


    
    public function getTagsDataList()
    {
        return ['游泳' => __('游泳'), '爬山' => __('爬山'), '跳舞' => __('跳舞')];
    }

    public function getStatusDataList()
    {
        return ['1' => __('显示'), '0' => __('隐藏')];
    }


    public function getTagsDataTextAttr($value, $data)
    {
        $value = $value ?: ($data['tags_data'] ?? '');
        $valueArr = explode(',', $value);
        $list = $this->getTagsDataList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }


    public function getStatusDataTextAttr($value, $data)
    {
        $value = $value ?: ($data['status_data'] ?? '');
        $list = $this->getStatusDataList();
        return $list[$value] ?? '';
    }

    protected function setTagsDataAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 关联分类
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id');
    }

}
